package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.AccumulatorProduct;
import com.apes.autoparts.product.model.BrandProduct;
import com.apes.autoparts.product.model.OilyProduct;
import com.apes.autoparts.product.repository.OilyProductRepository;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：机油类标准商品服务类
 *
 * @ClassName OilyProductService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/10/26 17:47
 * @Version 1.0
 */
@Service
public class OilyProductService extends DomainService {

    @Autowired
    private OilyProductRepository oilyProductRepository;

    @Autowired
    private ProductDao productDao;

    /**
     * 批量更新、新增、删除
     *
     * @param request
     * @return
     */
    public Map edit(SimpleRequest request) {
        //新增和修改
        List<OilyProduct> oilyProducts = request.getA("oilyProductItems", OilyProduct.class);
        Set<String> brandPrioritySet = new HashSet<>();

        //根据id判断新增
        List<OilyProduct> newOilyProduct = oilyProducts.stream().filter(oilyProduct -> Objects.isNull(oilyProduct.getId()) || "0".equals(oilyProduct.getId()))
                .collect(Collectors.toList());

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))) {
            List<OilyProduct> delOilyProducts = request.getA("del", OilyProduct.class);
            delOilyProducts.forEach(oilyProduct -> {
                String sole = oilyProduct.getBrand() + oilyProduct.getName() + oilyProduct.getUnit() + oilyProduct.getApiClass();
                if (Objects.nonNull(oilyProduct.getId()) && brandPrioritySet.add(sole)) {
                    oilyProductRepository.delete(oilyProduct);
                }
            });
        }
        //批量插入机油类标准商品
        productDao.oilyBatchInsert(newOilyProduct);

        return MapUtil.mapper("oilyProductItems", newOilyProduct);
    }

    /**
     * 定制导入品牌标准商品
     *
     * @param request
     */
    public JSONObject importOilyProduct(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     *
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();
        JSONArray titleArray = new JSONArray(13);
        titleArray.add("品牌");
        titleArray.add("零件名称");
        titleArray.add("单位");
        titleArray.add("系列");
        titleArray.add("型号");
        titleArray.add("容量[L]");
        titleArray.add("API等级");
        titleArray.add("粘度等级");
        titleArray.add("类型");
        titleArray.add("机油类型");
        titleArray.add("产品描述");
        titleArray.add("条形码");
        titleArray.add("ERP商品编码");
        titleColumnArray.add(titleArray);

        List<OilyProduct> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            if (((JSONArray) importDataValueArray.get(0)).size() != 13) throw new RuntimeException("导入模板错误，请检查文件并重新上传！");

            importDataValueArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() <= 3) return;

                String brand = "";
                String name = "";
                String unit = "";
                String catena = "";
                String modelNumber = "";
                String capacity = "";
                String apiClass = "";
                String viscosityClass = "";
                String type = "";
                String engineOilType = "";
                String description = "";
                String barCode = "";
                String ERPProductId = "";

                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0:
                            brand = iValueArray.getString(0);
                            break;
                        case 1:
                            name = iValueArray.getString(1);
                            break;
                        case 2:
                            unit = iValueArray.getString(2);
                            break;
                        case 3:
                            catena = iValueArray.getString(3);
                            break;
                        case 4:
                            modelNumber = iValueArray.getString(4);
                            break;
                        case 5:
                            capacity = iValueArray.getString(5);
                            break;
                        case 6:
                            apiClass = iValueArray.getString(6);
                            break;
                        case 7:
                            viscosityClass = iValueArray.getString(7);
                            break;
                        case 8:
                            type = iValueArray.getString(8);
                            break;
                        case 9:
                            engineOilType = iValueArray.getString(9);
                            break;
                        case 10:
                            description = iValueArray.getString(10);
                            break;
                        case 11:
                            barCode = iValueArray.getString(11);
                            break;
                        case 12:
                            ERPProductId = iValueArray.getString(12);
                            break;
                    }
                }
                //跳过首行标题行
                if ("品牌".equals(brand) || "零件名称".equals(name)) return;
                //if (!stringHashSet.add( brand + viscosityClass+apiClass+type+capacity)) throw new RuntimeException("导入重复数据，请重新导入！");
                OilyProduct oilyProduct = new OilyProduct();
                oilyProduct.setBrand(brand);
                oilyProduct.setName(name);
                oilyProduct.setUnit(unit);
                oilyProduct.setCatena(catena);
                oilyProduct.setModelNumber(modelNumber);
                if(!"".equals(capacity)){
                    oilyProduct.setCapacity(Double.valueOf(capacity));
                }
                oilyProduct.setApiClass(apiClass);
                oilyProduct.setViscosityClass(viscosityClass);
                oilyProduct.setType(type);
                oilyProduct.setEngineOilType(engineOilType);
                oilyProduct.setDescription(description);
                oilyProduct.setBarCode(barCode);
                oilyProduct.setERPProductId(ERPProductId);
                dataList.add(oilyProduct);
            });
        });

        productDao.oilyBatchInsert(dataList);
        return key.get();
    }

    /**
     * 放弃编辑回显当前数据
     *
     * @param request
     * @return
     */
    public Map oilyProductFindOne(SimpleRequest request) {
        List<OilyProduct> list = request.getA("oilyProductItems", OilyProduct.class);
        return MapUtil.mapper("oilyProductItems", list);
    }

    /**
     * 动态条件查询
     *
     * @param request
     */
    public Map conditionQuery(SimpleRequest request) {
        JSONObject jo = request.getJO();

        String brand = jo.getString("brand");
        String name = jo.getString("name");
        String unit = jo.getString("unit");
        String catena = jo.getString("catena");
        String modelNumber = jo.getString("modelNumber");
        String capacity = jo.getString("capacity");
        String apiClass = jo.getString("apiClass");
        String viscosityClass = jo.getString("viscosityClass");
        String type = jo.getString("type");
        String engineOilType = jo.getString("engineOilType");
        int page = jo.getInteger("page") < 0 || jo.getInteger("page")==null  ? 0 : jo.getInteger("page");

        if ("".equals(brand)) brand = null;
        if ("".equals(name)) name = null;
        if ("".equals(unit)) unit = null;
        if ("".equals(catena)) catena = null;
        if ("".equals(modelNumber)) modelNumber = null;
        if ("".equals(capacity)) capacity = null;
        if ("".equals(apiClass)) apiClass = null;
        if ("".equals(viscosityClass)) viscosityClass = null;
        if ("".equals(type)) type = null;
        if ("".equals(engineOilType)) engineOilType = null;

        if (isAllNotEmpty(brand, name, unit, catena, modelNumber, capacity, apiClass, viscosityClass, type, engineOilType)) {
            Page<OilyProduct> oilyProductPage = oilyProductRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", oilyProductPage.getContent(), "page", page, "sum", oilyProductPage.getTotalPages());
        }

        Page<OilyProduct> oilyProductPage = oilyProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "brand", "EQ", brand,
                "unit", "EQ", unit,
                "catena", "EQ", catena,
                "modelNumber", "EQ", modelNumber,
                "capacity", "EQ", capacity,
                "apiClass", "EQ", apiClass,
                "viscosityClass", "EQ", viscosityClass,
                "type", "EQ", type,
                "engineOilType", "EQ", engineOilType), PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", oilyProductPage.getContent(), "page", page, "sum", oilyProductPage.getTotalPages());
    }



    /**
     * 下载
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String brand = condition.getString("brand");
        String name = condition.getString("name");
        String unit = condition.getString("unit");
        String catena = condition.getString("catena");
        String modelNumber = condition.getString("modelNumber");
        String capacity = condition.getString("capacity");
        String apiClass = condition.getString("apiClass");
        String viscosityClass = condition.getString("viscosityClass");
        String type = condition.getString("type");
        String engineOilType = condition.getString("engineOilType");
        if ("".equals(brand)) brand = null;
        if ("".equals(name)) name = null;
        if ("".equals(unit)) unit = null;
        if ("".equals(catena)) catena = null;
        if ("".equals(modelNumber)) modelNumber = null;
        if ("".equals(capacity)) capacity = null;
        if ("".equals(apiClass)) apiClass = null;
        if ("".equals(viscosityClass)) viscosityClass = null;
        if ("".equals(type)) type = null;
        if ("".equals(engineOilType)) engineOilType = null;

        Page<OilyProduct> page = oilyProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("brand", "EQ", brand,
                "name", "EQ", name,
                "unit", "EQ", unit,
                "catena", "EQ", catena,
                "modelNumber", "EQ", modelNumber,
                "capacity", "EQ", capacity,
                "apiClass", "EQ", apiClass,
                "viscosityClass", "EQ", viscosityClass,
                "type", "EQ", type,
                "engineOilType", "EQ", engineOilType),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }



    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delOilyProduct(SimpleRequest request){
        List<OilyProduct> oilyProducts = request.getA("del", OilyProduct.class);
        for (OilyProduct oilyProduct : oilyProducts) {
            oilyProductRepository.delete(oilyProduct);
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 添加
     * @param request
     * @return
     */
    public OilyProduct insertOilyProduct(SimpleRequest request){
        JSONObject jo = request.getJO();
        OilyProduct oilyProduct  = jo.getObject("data",OilyProduct.class);
        return oilyProductRepository.saveAndFlush(oilyProduct);
    }

    private boolean isAllNotEmpty(String... strings) {
        if (strings.length == 0) {
            return false;
        }
        for (Object obj : strings) {
            if (Objects.isNull(obj)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 根据品牌+粘度等级+api类型+类型+容量获取机油类标准商品商品
     * @param request
     * @return
     */
    public OilyProduct getOilyProduct(SimpleRequest request){
        JSONObject param = request.getJO();
        String brand = param.getString("brand");
        String viscosityClass = param.getString("viscosityClass");
        String apiClass = param.getString("apiClass");
        String type = param.getString("type");
        Double capacity = param.getDouble("capacity");
        return oilyProductRepository.findByBrand(brand, viscosityClass, apiClass, type, capacity);
    }
}
